<template>
  <view class="content">
    <view class="containerBase">
      <uniZegoPusher v-if="livePusherUrl" ref="zegoPusher" :streamID="livePusherStreamID" :url="livePusherUrl" @statechange="statechange"></uniZegoPusher>
      <uniZegoPlayer
        v-for="streamItem in livePlayerList"
        :ref="streamItem.streamID"
        :url="streamItem.url"
        :streamID="streamItem.streamID"
        :key="streamItem.streamID"
      ></uniZegoPlayer>
    </view>
    <view class="index-container">
      <view class="input-container">
        <input v-model="roomID" placeholder="请输入房间 ID" placeholder-style="color: #b3b3b3; font-size: 14px;" class="room-input" />
        <text class="tip"></text>
      </view>
      <view class="button-container">
        <button @click="openRoom(1)" class="roomBtn">加入房间(推流)</button>
        <button @click="openRoom(0)" class="roomBtn">加入房间(不推流)</button>
        <button @click="stopPublish()" class="roomBtn">停止推流</button>
        <button @click="sendCustomCommand()" class="roomBtn">发送消息</button>
        <button @click="logout">退出房间</button>
      </view>
    </view>
    <view class="settings">
      <button v-if="isSettingShow" open-type="openSetting" @openSetting="settingCallback">
        授权使用摄像头和麦克风
      </button>
    </view>
  </view>
</template>

<script>
import { CommonExpress } from "../../utils/wxmini/common"
import { uniZegoPusher } from "../../components/uni-zego-pusher/uniZegoPusher.vue"
import { uniZegoPlayer } from "../../components/uni-zego-player/uniZegoPlayer.vue"
export default {
  data() {
    return {
      commonExpress: {},
      roomID: "126",
      livePusherUrl: "", // 推流地址
      livePusherStreamID: "", // 推流ID

      isSettingShow: false,
      livePlayerList: [] //  [{streamID,url}]
    }
  },
  components: {
    uniZegoPusher,
    uniZegoPlayer
  },
  methods: {
    async openRoom(type) {
      // 0 不推流 1 推流
      await this.commonExpress.login(this.roomID)
      if (type === 1) {
        // 获取到推流地址 推流流地址
        const { url, streamID } = await this.commonExpress.getPublishStream()
        this.livePusherUrl = url
        this.livePusherStreamID = streamID
      }
    },
    // 推流组件状态回调
    statechange(e) {
      console.log("mytag e.detail", e.detail)
    },

    async sendCustomCommand(msg) {
      const toUserList = this.commonExpress.roomUserList.map((item) => {
        return item.userID
      })
      console.log("mytag toUserList", toUserList)
      try {
        await this.commonExpress.zegoApi.sendBroadcastMessage(this.roomID, "小程序发送自定义消息" + (msg ? msg : ""))
      } catch (error) {
        console.error(error)
      }
    },

    // 停止推流
    async stopPublish() {
      try {
        await this.$refs.zegoPusher.stopPublishingStream(this.livePusherStreamID)
        this.livePusherUrl = null
        this.livePusherStreamID = null
      } catch (error) {
        console.log("mytag stopPublish error", error)
      }
    },

    async logout() {
      try {
        // 停止推流
        if (this.livePusherStreamID && this.livePusherUrl) {
          this.stopPublish()
        }
        // 停止拉流
        this.livePlayerList.forEach((item) => {
          this.$refs[item.streamID][0].stopPlayingStream(item.streamID)
        })
        this.livePlayerList = []

        // 退出房间服务
        const res = await this.commonExpress.zegoApi.logoutRoom()
        uni.navigateBack()
      } catch (error) {
        console.log("mytag logout error", error)
      }
    },
    // 用户拒绝授权之后，再次申请权限
    settingCallback(e) {
      if (e.errMsg.includes("ok")) {
        this.isSettingShow = false
      }
    },
    async initCommon() {
      // 初始化 expressApi
      this.commonExpress = new CommonExpress()
      // 检查 摄像头和 麦克风能力
      const checkRes = await this.commonExpress.checkSystemRequirements()
      this.livePlayerList = this.commonExpress.livePlayerList // 与 commonExpress中的 livePlayerList进行深拷贝。
      if (!checkRes) this.isSettingShow = true
    }
  },
  onHide() {
    this.sendCustomCommand("onhide")
    let timer = 1
    setTimeout(() => {
      this.sendCustomCommand("onhide after :", timer * 200 + 'ms')
      timer++
    }, 200)
  },
  mounted() {},
  async created() {
    this.initCommon()
  }
}
</script>

<style>
.containerBase {
  height: 73vh;
  max-height: 500px;
  padding: 10rpx;
}

.index-container {
  border-top: 1px slategrey solid;
}
.input-container {
  text-align: center;
}
.button-container {
  border-top: 1px slategrey solid;
}
.room-input {
  height: 80rpx;
  border-bottom: 1px solid rgba(13, 112, 255, 0.5);
}
button[type="primary"] {
  background-color: red;
}

.roomBtn {
  display: inline-block;
  width: 48vw;
  margin: 7rpx;
  background: rgba(13, 112, 255, 0.5);
  color: #fff;
}
</style>
